package com.springboot.blog.config;


import com.springboot.blog.beans.AdminUser;
import com.springboot.blog.dao.AdminUserDao;
import com.springboot.blog.dao.PermissionDao;
import com.springboot.blog.dao.RoleDao;
import lombok.SneakyThrows;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;
import java.util.Set;

/**
 * 1、创建一个类继承AuthorizingRealm
 * 2、重写两个方法
 * 3、重写getName方法，返回当前Realm的自定义名称
 */
public class MyRealm extends AuthorizingRealm {

    @Resource
    private AdminUserDao adminUserDao;
    @Resource
    private RoleDao roleDao;
    @Resource
    private PermissionDao permissionDao;

    public String getName(){
        return "myRealm";
    }

    /**
     * 获取授权数据
     */
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取当前用户用户名
        String  username = (String) principalCollection.iterator().next();
        //根据用户名查询当前用户的角色列表
        Set<String> rolename = roleDao.queryRoleNamesByUsername(username);
        //根据用户名查询当前用户的权限列表
        Set<String> ps = permissionDao.queryPermissionByUsername(username);
        System.out.println("==============查询角色权限信息====================");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(rolename);
        info.setStringPermissions(ps);
        return info;
    }

    /**
     * 获取认证数据
     */
    @SneakyThrows
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //从token中获取用户名
        UsernamePasswordToken token  = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();

        //根据用户名，从数据库查询当前用户名的安全数据
        AdminUser adminUser = adminUserDao.queryUserByUsername(username);
        if (adminUser == null){
            return null;
        }
        /**
         * username ： 当前用户用户名
         * user.getUserPwd() ： 从数据库查询出来的安全密码
         */
//        AuthenticationInfo info = new SimpleAuthenticationInfo(username,user.getUserPwd(),getName());
        //如果数据库中用户的密码是加了盐的
        AuthenticationInfo info = new SimpleAuthenticationInfo(username,adminUser.getBlogPassword(), ByteSource.Util.bytes(adminUser.getBlogPwdSalt()),getName());
        return info;
    }
}
